package com.drinks.yiniang.ui.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.drinks.yiniang.R;
import com.drinks.yiniang.common.help.UserTokenSingleton;
import com.drinks.yiniang.common.listener.OnHomeNavigationBarClickListener;
import com.drinks.yiniang.common.listener.OnHomePageApiRequestListener;
import com.drinks.yiniang.common.listener.OnLocationChangesListener;
import com.drinks.yiniang.common.location.MyLocationManager;
import com.drinks.yiniang.entity.tab.TabbarEntity;
import com.drinks.yiniang.io.service.DownloadService;
import com.drinks.yiniang.ui.activity.message.MessageActivity;
import com.drinks.yiniang.ui.activity.search.SearchGoodsActivity;
import com.drinks.yiniang.ui.fragment.category.CategoryPageFragment;
import com.drinks.yiniang.ui.fragment.community.CommunityPageFragment;
import com.drinks.yiniang.ui.fragment.home.HomePageFragment;
import com.drinks.yiniang.ui.fragment.shopping.ShoppingCartPageFragment;
import com.drinks.yiniang.ui.fragment.user.UserCenterPageFragment;
import com.drinks.yiniang.ui.widget.nav.TabBarLayout;
import com.drinks.yiniang.ui.widget.pop.LocationPopup;
import com.drinks.yiniang.utils.ActivityUtils;
import com.drinks.yiniang.utils.FileUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.listener.OnSureCancelListener;
import com.hansen.library.permission.MPermission;
import com.hansen.library.permission.annotation.OnMPermissionDenied;
import com.hansen.library.permission.annotation.OnMPermissionGranted;
import com.hansen.library.permission.annotation.OnMPermissionNeverAskAgain;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.ui.fragment.BaseFragment;
import com.hansen.library.ui.widget.dialog.MaterialDialog;
import com.hansen.library.ui.widget.layout.StatusToolsBarView;
import com.hansen.library.utils.LogUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页
 *
 * @author han
 * @date 2019/08/26
 */
public class MainActivity extends BaseTranBarActivity implements OnHomeNavigationBarClickListener,
        TabBarLayout.OnTabbarClickListener, OnLocationChangesListener, OnSureCancelListener, OnHomePageApiRequestListener {

    private static final int REQ_INSTALL_PERMISSION = 0x01;
    private static final int BASIC_PERMISSION_REQUEST_CODE = 10000;

    private final int TYPE_UPDATE_DIALOG = 0x01;//更新dialog
    private final int TYPE_PERMISSION_DIALOG = 0x02;//安装未知应用权限dialog

    //顶部view, 用于地址popwindow定位
    private StatusToolsBarView v_home_nav_bar;
    //底部tab bar
    private TabBarLayout tab_bar_main;

    //首页
    private HomePageFragment mHomePageFragment;
    //分类页面
    private CategoryPageFragment mCategoryPageFragment;
    //社区页面
    private CommunityPageFragment mCommunityPageFragment;
    //购物车页面
    private ShoppingCartPageFragment mShoppingCartPageFragment;
    //用户中心页面
    private UserCenterPageFragment mUserCenterPageFragment;
    //当前fragment
    private BaseFragment mCurrentFragment;

    private MyLocationManager mLocationManager;

    private LocationPopup mLocationPopup;

    //更新提示
    private MaterialDialog mUpdateVersionDialog;

    //地址
    private String mLocationAddress;
    //新版版本名称
    private String mVersionName;
    //新版下载地址
    private String mDownloadUrl;

    /**
     * 基本权限管理
     */
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    @Override
    protected void initView() {
        v_home_nav_bar = findViewById(R.id.v_home_nav_bar);

        tab_bar_main = findViewById(R.id.tab_bar_main);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        // 从堆栈恢复，不再重复解析之前的intent
        if (savedInstanceState != null) {
            setIntent(new Intent());
        }

        mContext = this;

        initTabBarList();
        initHomeFragment();
        requestBasicPermission();
        mLocationManager = MyLocationManager.getInstance(mContext);
        //开始定位
        mLocationManager.initLocation();
        mLocationManager.startLocation();

        if (getIntent() != null) {
            mVersionName = getIntent().getStringExtra(Constants.KeyName);
            mDownloadUrl = getIntent().getStringExtra(Constants.KeyUrl);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if(getIntent() != null) {
            //跳转到购物车
            if(getIntent().getBooleanExtra(Constants.KeyJumpToShoppingCartPage, false)) {
                tab_bar_main.changeTabBar(3);
                toShoppingCartPage();
            } else if(getIntent().getBooleanExtra(Constants.KeyJumpToHomePage, false)) {
                tab_bar_main.changeTabBar(0);
                toHomePage();
            }
        }
    }

    @Override
    protected void initListener() {
        tab_bar_main.setOnTabbarClickListener(this);
        mLocationManager.setLocationChangeListener(this);
    }

    @Override
    public void widgetClick(View v) {

    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_main;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.clear();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onTabbarClickListener(View v, int pos) {
        switch (pos) {
            case 0: //首页
                toHomePage();
                return false;
            case 1: //分类
                toCategoryPage();
                return false;
            case 2: //社区页面
                toCommunityPage();
                return false;
            case 3://购物车页面
                if(!ActivityUtils.isLogined(this, true)) {
                    return true;
                }
                toShoppingCartPage();
                return false;
            case 4://个人中心
                if(!ActivityUtils.isLogined(this, true)) {
                    return true;
                }
                toUserPage();
                return false;
            default:
                return false;
        }
    }

    private void initTabBarList() {
        List<TabbarEntity> mTabbarList = new ArrayList<>(5);

        mTabbarList.add(new TabbarEntity(R.string.text_main_home, R.mipmap.icon_tab_home_n, R.mipmap.icon_tab_home_p));
        mTabbarList.add(new TabbarEntity(R.string.text_category, R.mipmap.icon_tab_category_n, R.mipmap.icon_tab_category_p));
        mTabbarList.add(new TabbarEntity(R.string.text_community, R.mipmap.icon_tab_community_n, R.mipmap.icon_tab_community_p));
        mTabbarList.add(new TabbarEntity(R.string.text_shopping_cart, R.mipmap.icon_tab_cart_n, R.mipmap.icon_tab_cart_p));
        mTabbarList.add(new TabbarEntity(R.string.text_my, R.mipmap.icon_tab_me_n, R.mipmap.icon_tab_me_p));

        tab_bar_main.setTabbarData(mTabbarList);
    }

    //初始化首页fragment
    private void initHomeFragment() {
        if (mHomePageFragment == null) {
            mHomePageFragment = HomePageFragment.newInstance();
        }

        mCurrentFragment = addFragment(mHomePageFragment, R.id.fl_main);
    }

    //切换到首页
    private void toHomePage() {
        if (mHomePageFragment == null) {
            mHomePageFragment = HomePageFragment.newInstance();
        }

        mCurrentFragment = switchFragment(mCurrentFragment, mHomePageFragment, R.id.fl_main);
    }

    //切换到商品分类页面
    private void toCategoryPage() {
        if (mCategoryPageFragment == null) {
            mCategoryPageFragment = CategoryPageFragment.newInstance();
        }

        mCurrentFragment = switchFragment(mCurrentFragment, mCategoryPageFragment, R.id.fl_main);
    }

    //切换到社区页面
    private void toCommunityPage() {
        if (mCommunityPageFragment == null) {
            mCommunityPageFragment = CommunityPageFragment.newInstance();
        }

        mCurrentFragment = switchFragment(mCurrentFragment, mCommunityPageFragment, R.id.fl_main);
    }

    //切换到购物车页面
    private void toShoppingCartPage() {
        if (mShoppingCartPageFragment == null) {
            mShoppingCartPageFragment = ShoppingCartPageFragment.newInstance();
        }

        mCurrentFragment = switchFragment(mCurrentFragment, mShoppingCartPageFragment, R.id.fl_main);
    }

    //切换到个人中心
    private void toUserPage() {
        if (mUserCenterPageFragment == null) {
            mUserCenterPageFragment = UserCenterPageFragment.newInstance();
        }

        mCurrentFragment = switchFragment(mCurrentFragment, mUserCenterPageFragment, R.id.fl_main);
    }

    @Override
    public void onAddress(View v) {
        showLocationPop();
    }

    @Override
    public void onSearchClick(View v) {
        Intent intent = new Intent(mContext, SearchGoodsActivity.class);
        startActivity(intent);
    }

    @Override
    public void onMessage(View v) {
        if(!ActivityUtils.isLogined(this, true)) {
            return;
        }
        Intent intent = new Intent(mContext, MessageActivity.class);
        startActivity(intent);
    }

    private void requestBasicPermission() {
        MPermission.printMPermissionResult(true, this, BASIC_PERMISSIONS);
        MPermission.with(MainActivity.this)
                .setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }


    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {
        try {
            LogUtils.e("授权成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        MPermission.printMPermissionResult(false, this, BASIC_PERMISSIONS);
    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
        try {
            LogUtils.e("未全部授权，部分功能可能无法正常运行！");
        } catch (Exception e) {
            e.printStackTrace();
        }

        MPermission.printMPermissionResult(false, this, BASIC_PERMISSIONS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQ_INSTALL_PERMISSION) {//以防万一，再次检查权限
            if (checkInstallApkPermission()) {//有权限
                startDownloadApkService();
            }
        }
    }

    //定位相关
    @Override
    public void locationChange(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                mLocationAddress = aMapLocation.getStreet() + aMapLocation.getPoiName();
            }
        }
    }

    private void showLocationPop() {
        if(StringUtils.isEmpty(mLocationAddress)) {
            ToastUtils.showShort(R.string.text_location_dot);
            return;
        }

        if(mLocationPopup == null) {
            mLocationPopup = new LocationPopup();
        }

        mLocationPopup.showLocationPop(v_home_nav_bar, mContext);
        mLocationPopup.setPopupLocationAddress(mLocationAddress);
    }

    @Override
    public void onSure(int type, String value) {
        switch (type) {
            case TYPE_UPDATE_DIALOG://下载更新
                if (checkInstallApkPermission()) {//有权限
                    startDownloadApkService();
                }
                break;
            case TYPE_PERMISSION_DIALOG://权限
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    toInStallPermissionSettingActivity();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onCancel(int type) {
        mVersionName = null;
        mDownloadUrl = null;
        if (TYPE_PERMISSION_DIALOG == type) {
            ToastUtils.showShort(getString(R.string.text_refund_install_permission));
        }
    }

    @Override
    public void OnHomePageApiRequestSuccess() {
        initUpdateVersionDialog(TYPE_UPDATE_DIALOG, null, getString(R.string.text_update_app_tips), Constants.TAG_TIPS_DIALOG);
    }

    private void startDownloadApkService() {
        if (!StringUtils.isHttp(mDownloadUrl)) {
            ToastUtils.showShort(getString(R.string.text_error_download_url));
            return;
        }

        Intent intent = new Intent(mContext, DownloadService.class);
        intent.putExtra(Constants.KeyUrl, mDownloadUrl);
        intent.putExtra(Constants.KeyName, mVersionName);
        startService(intent);
    }

    //更新版本或权限提示
    private void initUpdateVersionDialog(int type, String title, String content, String tag) {
        if (mVersionName != null && StringUtils.isHttp(mDownloadUrl)) {
            mUpdateVersionDialog = MaterialDialog.newInstance(type, title, content);

            mUpdateVersionDialog.show(getSupportFragmentManager(), tag);
        }
    }

    private boolean checkInstallApkPermission() {
        if (!FileUtils.checkInstallPakPermission(mContext)) {
            initUpdateVersionDialog(TYPE_PERMISSION_DIALOG, getString(R.string.text_open_install_permission), getString(R.string.text_install_unkonw_apk_permission), Constants.TAG_TIPS_PERMISSION);
            return false;
        }

        return true;
    }

    @TargetApi(android.os.Build.VERSION_CODES.O)
    private void toInStallPermissionSettingActivity() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        startActivityForResult(intent, REQ_INSTALL_PERMISSION);
    }

    @Override
    protected void onDestroy() {
        //清除单类
        UserTokenSingleton.getInstance().setGlobalUserToken(null);

        mLocationManager.stopLocation();
        mLocationManager.destroyLocation();

        mHomePageFragment = null;
        mCategoryPageFragment = null;
        mCommunityPageFragment = null;
        mShoppingCartPageFragment = null;
        mUserCenterPageFragment = null;
        mCurrentFragment = null;
        mUpdateVersionDialog = null;

        super.onDestroy();
    }
}
